package net.quux00;

import java.io.*;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WriteMerkle {

    public static void main(String[] args) throws Exception {

        while(true) {
            writeMerkle();
        }

    }
    static File merklerFile = null;
    static List<String> signatures = new ArrayList<String>();
    public static void writeMerkle() throws Exception {
        Date now = new Date();
        long time = 30*60*1000;//2分钟
        Date beforeDate = new Date(now .getTime() - time);//2分钟前的时间
        SimpleDateFormat dateFormatMinute= new SimpleDateFormat("yyyy-MM-dd-HH-mm");
        String  minute = dateFormatMinute.format( beforeDate );
        SimpleDateFormat dateFormatHour= new SimpleDateFormat("yyyy-MM-dd-HH");
        String  hour = dateFormatHour.format( beforeDate );

        File file = new File("d:\\log_dir\\"+hour+"\\"+minute);
        if (file.exists()) {
            String hashCode = getFileSHA512(file);
            System.out.println(file.getName() +" hash code is:"+hashCode);
            signatures.add(hashCode);
            if(signatures.size()==2){
                MerkleTree leaf = new MerkleTree(signatures);
                byte[] serializedTree = leaf.serialize();
                writeFileByBytes("d:\\log_dir\\merkler",serializedTree,true);
                signatures.clear();
            }
        }

    }
    public static String getFileSHA512(File file) {
        String str = "";
        try {
            str = getHash(file, "SHA-256");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
    public static String getHash(File file, String hashType) throws Exception {
        InputStream fis = new FileInputStream(file);
        byte buffer[] = new byte[1024];
        MessageDigest md5 = MessageDigest.getInstance(hashType);
        for (int numRead = 0; (numRead = fis.read(buffer)) > 0; ) {
            md5.update(buffer, 0, numRead);
        }
        fis.close();
        return toHexString(md5.digest());
    }
    public static String toHexString(byte b[]) {
        StringBuilder sb = new StringBuilder();
        for (byte aB : b) {
            sb.append(Integer.toHexString(aB & 0xFF));
        }
        return sb.toString();
    }
    /**
     * 向文件写入byte[]
     *
     * @param fileName 文件名
     * @param bytes    字节内容
     * @param append   是否追加
     * @throws IOException
     */
    public static void writeFileByBytes(String fileName, byte[] bytes, boolean append) throws IOException {
        try(OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName, append))){
            out.write(bytes);
        }
    }


}

